package com.zhitan.ems.app.patrol.controller;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhitan.ems.app.patrol.entity.PatrolEntity;
import com.zhitan.ems.app.patrol.entity.PatrolNoticeEntity;
import com.zhitan.ems.app.patrol.service.PatrolNoticeService;
import com.zhitan.ems.app.patrol.service.PatrolService;
import com.zhitan.ems.app.patrol.vo.PatrolNoticeVO;
import com.zhitan.ems.app.patrol.wrapper.PatrolNoticeWrapper;
import com.zhitan.ems.common.annotation.Log;
import com.zhitan.ems.common.core.controller.BaseController;
import com.zhitan.ems.common.core.domain.R;
import com.zhitan.ems.common.enums.BusinessType;
import com.zhitan.ems.common.utils.DateUtils;
import com.zhitan.ems.common.utils.StringUtils;
import com.zhitan.ems.framework.core.vo.VPage;
import com.zhitan.ems.framework.core.vo.VQueryKit;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
 * 上报消息
 * @author zhitan
 * 
 * @date 2024-11-02 14:05:24
 */
@Api(tags = "PC管理--巡检--上报消息", value = "上报消息")
@RestController
@RequestMapping("intra/patrol/patrolnotice")
public class PatrolNoticeController extends BaseController{
    @Autowired
    private PatrolNoticeService patrolNoticeService;
    @Autowired
    private PatrolService patrolService;
    /**
     * 列表
     */
    @ApiOperation(value = "列表", response = VPage.class)
    @ApiImplicitParams({
		        @ApiImplicitParam(name = "name", value = "标题",  paramType = "query", required = false, dataType =  "String"),
		})
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('patrol:patrolnotice:list')")
    public R<VPage<PatrolNoticeVO>> list(@RequestParam Map<String, Object> params){
        QueryWrapper<PatrolNoticeEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), PatrolNoticeEntity.class);
        queryWrapper.orderByDesc("id");
         queryWrapper.like(StringUtils.isNotNull(params.get("name")),"name", params.get("name"));
        IPage<PatrolNoticeEntity> pages = patrolNoticeService.page(VQueryKit.getPage(params), queryWrapper);
        return R.data(PatrolNoticeWrapper.build().toVPageVO(pages));
    }
    @GetMapping("/listStat")
    @PreAuthorize("@ss.hasPermi('patrol:patrolnotice:list')")
    public R<Map<String, Object>> listStat(@RequestParam Map<String, Object> params)throws ParseException{
         QueryWrapper<PatrolNoticeEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), PatrolNoticeEntity.class);
         queryWrapper.select("count(id) as total,sum(id) as all");
         queryWrapper.like(StringUtils.isNotNull(params.get("name")),"name", params.get("name"));
        if(params.containsKey("createDate")) {
            queryWrapper.between("create_at",
                    DateUtils.getStartOfDate(DateUtils.str_ToDate(params.get("createDate").toString())),
                    DateUtils.getEndOfDate(DateUtils.str_ToDate(params.get("createDate").toString()))
              );   
        }
        Map<String, Object>  stat=patrolNoticeService.getMap(queryWrapper);
        return R.data(stat);
    }
    @ApiOperation(value = "统计消息", response = Map.class)
    @GetMapping("/queryStat")
    @PreAuthorize("@ss.hasPermi('patrol:patrol:list')")
    public R<Map<String, Object>> queryStat(@RequestParam Map<String, Object> params)throws ParseException{
         QueryWrapper<PatrolNoticeEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), PatrolNoticeEntity.class);
         queryWrapper.select("count(id) as total,sum(if(state=0,1,0)) as state1, sum(if(state=1,1,0)) as state0 ");
        if(params.containsKey("startDate")&&params.containsKey("endDate")) {
            queryWrapper.between("create_at",
                    DateUtils.getStartOfDate(DateUtils.strToDate(params.get("startDate").toString())),
                    DateUtils.getEndOfDate(DateUtils.strToDate(params.get("endDate").toString()))
              );   
         }
        Map<String, Object>  stat=patrolNoticeService.getMap(queryWrapper);
        return R.data(stat);
    }
    /**
     * 信息
     */
    @ApiOperation(value = "信息", response = PatrolNoticeVO.class)
    @GetMapping("/detail/{id}")
    @PreAuthorize("@ss.hasPermi('patrol:patrolnotice:info')")
    public R<PatrolNoticeVO> detail(@PathVariable("id") Long id){
		PatrolNoticeEntity patrolNotice = patrolNoticeService.getById(id);
	    return R.data(PatrolNoticeWrapper.build().entityVO(patrolNotice));
    }
     /**
     * 保存&更新
     */
    @Log(title = "上报消息", businessType = BusinessType.ADDANDEDIT)
    @ApiOperation(value = "保存&更新", response = Boolean.class)
    @PostMapping("/submit")
    @PreAuthorize("@ss.hasPermi('patrol:patrolnotice:save')")
    public R<PatrolNoticeVO> submit(@Valid @RequestBody PatrolNoticeVO patrolNotice){
   		if(patrolNotice.getId()==null) {
           return add(patrolNotice);
        }else {
           return edit(patrolNotice);
        }
    }
    @Log(title = "上报消息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "保存", response = Boolean.class)
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPermi('patrol:patrolnotice:save')")
    public R<PatrolNoticeVO> add(@Valid @RequestBody PatrolNoticeVO patrolNotice){
   		if(patrolNotice.getId()==null) {
            patrolNotice.setCreateAt(new Date());
            patrolNotice.setIsDelete(0);
            patrolNotice.setUpdateAt(new Date());
        } 
    	if(patrolNoticeService.save(patrolNotice)) {
    		if(patrolNotice.getPatrolId()!=null&&patrolNotice.getPatrolId()>0) {
    			PatrolEntity patrol = patrolService.getById(patrolNotice.getPatrolId());
    			if(patrol!=null) {
    				patrol.setNoticeReplayNum(patrol.getNoticeReplayNum()+1);
    				patrol.setUpdateAt(new Date());
    				patrolService.updateById(patrol);
    			}
    		}
    		return R.ok(patrolNotice);
    	 }
    	return R.error("数据错误");
    }
    @Log(title = "上报消息", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "更新", response = Boolean.class)
    @PostMapping("/edit")
    @PreAuthorize("@ss.hasPermi('patrol:patrolnotice:update')")
    public R<PatrolNoticeVO> edit(@Valid @RequestBody PatrolNoticeVO patrolNotice){
    	if(patrolNoticeService.updateById(patrolNotice)) {
    		if(patrolNotice.getPatrolId()!=null&&patrolNotice.getPatrolId()>0) {
    			PatrolEntity patrol = patrolService.getById(patrolNotice.getPatrolId());
    			if(patrol!=null) {
    				patrol.setNoticeReplayNum(patrol.getNoticeReplayNum()+1);
    				patrol.setUpdateAt(new Date());
    				patrolService.updateById(patrol);
    			}
    		}
    		return R.ok(patrolNotice);
    	 }
    	return R.error("数据错误");
    }
    /**
     * 删除
     */
    @ApiOperation(value = "删除", response = Boolean.class)
    @DeleteMapping("/delete")
    @PreAuthorize("@ss.hasPermi('patrol:patrolnotice:delete')")
    public R<Boolean> delete(@RequestBody Long[] ids){
        return R.ok(patrolNoticeService.removeByIds(Arrays.asList(ids)));
    }

}
